package com.bytz.modules.cms.order.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytz.common.api.vo.Result;
import com.bytz.common.system.base.controller.BytzController;
import com.bytz.common.system.query.QueryGenerator;
import com.bytz.common.util.SecurityUtils;
import com.bytz.modules.cms.c4c.model.C4cGetContacts;
import com.bytz.modules.cms.c4c.model.C4cOpportunity;
import com.bytz.modules.cms.common.constants.AdminAuthConstants;
import com.bytz.modules.cms.common.util.ExcelUtil;
import com.bytz.modules.cms.echop.service.IEChopService;
import com.bytz.modules.cms.order.entity.Order;
import com.bytz.modules.cms.order.model.AdminOrderModel;
import com.bytz.modules.cms.order.model.OrderExcel;
import com.bytz.modules.cms.order.model.OrderItemAuditAssist;
import com.bytz.modules.cms.order.model.OrderItemExcel;
import com.bytz.modules.cms.order.service.IAdminOrderService;
import com.bytz.modules.cms.product.constant.ProductConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "订单相关")
@RequestMapping("/order")
@PreAuthorize("hasAuthority('" + AdminAuthConstants.Order.EDIT + "')") //权限
public class OrderController extends BytzController<Order, IAdminOrderService> {

    @Autowired
    private IAdminOrderService orderService;

    @Autowired
    private IEChopService eChopService;

    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<AdminOrderModel> queryById(@RequestParam(value = "id") String id) {

        return Result.ok(orderService.queryById(id, SecurityUtils.hasAuthority(ProductConstants.Permission.COST_PRICE_VIEW)));
    }

    @ApiOperation(value = "分页查询", notes = "分页查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<AdminOrderModel>> page(Order order,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {

        return Result.ok(orderService.queryPage(
                new Page<>(pageNo, pageSize),
                QueryGenerator.initQueryWrapper(order, req.getParameterMap(), Order.class)
        ));
    }

    @ApiOperation(value = "上传盖章合同", notes = "如果e-chop没有回调成功，用这个接口可以上传合同，优先级比回调合同高")
    @RequestMapping(value = "/uploadContract", method = RequestMethod.POST)
    public Result<?> uploadContract(@RequestBody Order order) {

        orderService.uploadContract(order);
        return Result.ok();
    }

    @ApiOperation(value = "导入历史订单", notes = "导入历史订单")
    @PreAuthorize("hasAuthority('" + AdminAuthConstants.Order.IMPORT + "')")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @SuppressWarnings("unchecked")
    public Result<?> importExcel(HttpServletRequest request) {

        HashMap<String, Class<?>> map = new HashMap<>();
        map.put("order", OrderExcel.class);
        map.put("orderItem", OrderItemExcel.class);

        Map<String, List<?>> excels = ExcelUtil.importGroupBySheetName(request, map);
        List<OrderExcel> orderExcels = (List<OrderExcel>) excels.get("order");
        List<OrderItemExcel> orderItemExcels = (List<OrderItemExcel>) excels.get("orderItem");

        return Result.ok(orderService.importHistory(orderExcels, orderItemExcels));
    }

    @ApiOperation(value = "获取导入模板", notes = "获取导入模板")
    @RequestMapping(value = "/template", method = RequestMethod.POST)
    public void template(HttpServletResponse response) throws Exception {
        ExcelUtil.setDownloadHeader("历史订单导入模板.xlsx", response);
        Resource resource = new ClassPathResource("docx/历史订单导入模板.xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        IoUtil.copy(resource.getInputStream(), outputStream);
        outputStream.flush();
        outputStream.close();
    }

    @ApiOperation(value = "导出订单", notes = "导出订单")
    @RequestMapping(value = "/exportXls", method = RequestMethod.POST)
    public void export(Order order,
                       HttpServletRequest request,
                       HttpServletResponse response) throws Exception {

        orderService.export(QueryGenerator.initQueryWrapper(order, request.getParameterMap(), Order.class), response);
    }

    @ApiOperation(value = "订单历史审批价格", notes = "订单历史审批价格")
    @RequestMapping(value = "/product/history", method = RequestMethod.GET)
    public Result<OrderItemAuditAssist> productHistory(@RequestParam(value = "id") String orderId,
                                                       @RequestParam(value = "productNumber") String productNumber,
                                                       @RequestParam(value = "orderType") String orderType) {

        return Result.ok(orderService.productHistory(orderId, productNumber, orderType));
    }

    @ApiOperation(value = "根据订单获取待选opportunity", notes = "根据订单获取待选opportunity")
    @RequestMapping(value = "/opportunities", method = RequestMethod.GET)
    public Result<List<C4cOpportunity>> productHistory(@RequestParam String id) {
        return Result.ok(orderService.getOpportunities(id));
    }

    @ApiOperation(value = "订单绑定机会", notes = "需要传订单id、机会id、机会ObjectId")
    @RequestMapping(value = "/bindOpportunity", method = RequestMethod.POST)
    public Result<Boolean> bindOpportunity(@RequestParam Order order) {
        return Result.ok(orderService.bindOpportunity(order));
    }

    @ApiOperation(value = "下载合同", notes = "根据订单id下载合同")
    @RequestMapping(value = "/downloadContract", method = RequestMethod.GET)
    public Result<?> downloadContract(@RequestParam String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        eChopService.getContractByOrderId(id, request, response);
        return Result.ok();
    }

    @ApiOperation(value = "终止订单", notes = "终止订单")
    @RequestMapping(value = "/terminate", method = RequestMethod.POST)
    public Result<Boolean> terminate(@RequestParam String id) {
        return Result.ok(orderService.terminate(id));
    }
}